package com.sdksoft.readcard

import android.content.Intent
import android.util.Log
import android.view.View
import com.csht.bean.IdCardData
import com.csht.enums.ReadCardType
import com.csht.enums.StatusCode
import com.csht.listener.InitListener
import com.csht.listener.ReadCardListener
import com.sdksoft.readcard.databinding.ActivityNfcYjzBinding
import com.csht.utils.HHTipUtils
import com.csht.utils.NfcUtils
import org.json.JSONObject

/**
 * NFC 银行卡
 */
class NFCBankCardActivity : BaseInitActivity(), ReadCardListener {
    //1.声明一个nfc的Adapter
    private lateinit var nfcUtils: NfcUtils

    private val TAG = "readcard"

    private lateinit var activityNfcHuzhaoBinding: ActivityNfcYjzBinding

    private var isInitOk = false

    override fun initView() {
        super.initView()
        setTitleText("NFC银行卡")
        activityNfcHuzhaoBinding = ActivityNfcYjzBinding.inflate(layoutInflater)
        baseActivityBinding.llContent.apply{
            addView(activityNfcHuzhaoBinding.root, 0)
        }
        nfcUtils = NfcUtils(this,  this.javaClass)
        readSettingBuilder.buildReadCardType(ReadCardType.NFC)
        initSDK()
    }

    /**
     * 初始化SDK
     */
    private fun initSDK() {
        if (readCardManager.readCardType() === ReadCardType.NFC) {
            readCardManager.readCardInit(object : InitListener {
                override fun onResponse(code: Int, msg: String) {
                    when (code) {
                        StatusCode.ININ_ING.code -> {
                            Log.d(TAG, "初始化中. $msg")
                        }
                        StatusCode.ININ_OK.code -> {
                            isInitOk = true
                            runOnUiThread {
                                HHTipUtils.getInstance().showToast(this@NFCBankCardActivity, "初始化成功")
                            }
                        }
                        else -> {
                            isInitOk = false
                            runOnUiThread {
                                HHTipUtils.getInstance().showToast(this@NFCBankCardActivity, "初始化失败")
                            }
                        }
                    }
                }
            })
        }
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart")
        //此处adapter需要重新获取，否则无法获取message
        nfcUtils.nfcInit( this,  this.javaClass)
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume")
        //设置处理优于所有其他NFC的处理
        nfcUtils.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause")
        //恢复默认状态
        nfcUtils.onPause(this)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        if (isInitOk.not()) {
            HHTipUtils.getInstance().showToast(this@NFCBankCardActivity, "没有初始化成功")
            return
        }
        activityNfcHuzhaoBinding.apply {
            HHTipUtils.getInstance()
                .showProgressDialog(this@NFCBankCardActivity, "读取中，请勿移动", false)
            // 开始读取
            activityNfcHuzhaoBinding.tvMsg.text = "开始读卡---->"
            activityNfcHuzhaoBinding.ivHead.setImageResource(0)
            readCardManager.readCardStart(
                intent, this@NFCBankCardActivity
            )
        }
    }

    override fun onReadCardState(type: Int, msg: String?) {
        if (type == 1022) { //读卡失败
            HHTipUtils.getInstance().dismissProgressDialog()
        } else if(type == StatusCode.READCARD_SUCCESS.code){
            HHTipUtils.getInstance().dismissProgressDialog()
        }
        if (type != StatusCode.READCARD_SUCCESS.code) {
            activityNfcHuzhaoBinding.tvMsg.apply {
                append("\n状态码：$type")
                append("\n消息：$msg")
                append("\n-------------------------")
            }
            mainHandler.postDelayed(
                {
                    activityNfcHuzhaoBinding.logScroll.fullScroll(View.FOCUS_DOWN)
                },
                200
            )
        }
    }

    override fun onReadICCardSuccess(icNumber: String?, type: Int) {
        HHTipUtils.getInstance().dismissProgressDialog()
        activityNfcHuzhaoBinding.ivHead.setImageResource(0)
        activityNfcHuzhaoBinding.tvMsg.apply {
            text = "----读卡成功---->"
            append("\n卡类型：$type")
            append("\n-------------------------")
            if (type == StatusCode.CARD_BANK.code) { // 银行卡
                try {
                    icNumber?.let {
                        val jsonObject = JSONObject(icNumber)
                        append("\n卡号：${jsonObject.optString("cardNumber", "")}")
                        append("\n凭证号：${jsonObject.optString("certificateNum", "")}")
                        append("\n有效日期：${jsonObject.optString("validityTime", "")}")
                        val transDetail = jsonObject.getJSONArray("transDetail")
                        for (i in 0 until transDetail.length()) {
                            append("\n-------------------------")
                            val transDetailItem = transDetail.getJSONObject(i)
                            append("\n交易日期：${transDetailItem.optString("transactionDate", "")}")
                            append("\n交易时间：${transDetailItem.optString("transactionTime", "")}")
                            append("\n授权金额：${transDetailItem.optString("authorizedAmount", "")}")
                            append("\n其它金额：${transDetailItem.optString("otherAmount", "")}")
                            append("\n终端国家代码：${transDetailItem.optString("countryCode", "")}")
                            append("\n交易货币代码：${transDetailItem.optString("currencyCode", "")}")
                            append("\n商户名称：${transDetailItem.optString("merchantName", "")}")
                            append("\n交易类型：${transDetailItem.optString("transactionType", "")}")
                            append("\n应用交易计数器：${transDetailItem.optString("ATC", "")}")
                        }
                    }
                }catch (e: Exception){}
            } else {
                append("\n卡号：$icNumber")
            }
        }
    }

    override fun onReadIDCardSuccess(bean: IdCardData?) {
        HHTipUtils.getInstance().dismissProgressDialog()
    }

    override fun onDestroy() {
        super.onDestroy()
        HHTipUtils.getInstance().dismissProgressDialog()
        mainHandler.removeCallbacksAndMessages(null)
        readCardManager.readCardStop()
    }
}